package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;


    // 获取营业额
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        // 计算时间区间
        List<LocalDate> dateList = getDateList(begin, end);


        // 查询date日期对应的营业额 状态为 “已完成”
        List<Double> turnoverList = new ArrayList<>();

        for (LocalDate date : dateList) {
            // 计算每天的开始时间和结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            HashMap<Object, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);

            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }


        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    // 用户统计
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

        // 计算时间区间
        List<LocalDate> dateList = getDateList(begin, end);

        // 每天的用户总量
        List<Integer> totalUserList = new ArrayList<>();
        // 每天新增用户列表
        List<Integer> newUserList = new ArrayList<>();


        // 根据每天的起止时间去查询用户数量
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            HashMap<Object, Object> map = new HashMap<>();
            map.put("end", endTime);

            Integer totalUser = userMapper.getByMap(map);
            totalUserList.add(totalUser);

            map.put("begin", beginTime);
            Integer newUser = userMapper.getByMap(map);
            newUserList.add(newUser);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    //   订单统计
    @Override
    public OrderReportVO orderReportVO(LocalDate begin, LocalDate end) {
        // 计算时间区间
        List<LocalDate> dateList = getDateList(begin, end);

        //   每天订单总数
        List<Integer> orderCountList = new ArrayList<>();
        //   每天有效订单
        List<Integer> validOrderCountList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            HashMap<Object, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);

            Integer n1 = orderMapper.getByMap(map);
            orderCountList.add(n1);

            map.put("status", Orders.COMPLETED);
            Integer n2 = orderMapper.getByMap(map);
            validOrderCountList.add(n2);
        }

        // 订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        // 有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        //订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }


        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(orderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .build();

    }

    private List<LocalDate> getDateList(LocalDate begin,LocalDate end){
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }

    // 销量排名TOP10
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        // 计算时间区间
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        HashMap<Object, Object> map = new HashMap<>();
        map.put("begin",beginTime);
        map.put("end",endTime);
        map.put("status",Orders.COMPLETED);

        List<GoodsSalesDTO> goodsSalesDTO = orderMapper.getTop10(map);
        List<String> names = goodsSalesDTO.stream().map(GoodsSalesDTO::getName).toList();
        List<Integer> number = goodsSalesDTO.stream().map(GoodsSalesDTO::getNumber).toList();

        return SalesTop10ReportVO.
                builder().
                numberList(StringUtils.join(number,","))
                .nameList(StringUtils.join(names,","))
                .build();
    }

    // 导出数据

    @Override
    public void exportBusinessDate(HttpServletResponse response) throws IOException {
        // 1. 查询数据库，获取营业数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        LocalDateTime begin = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dateEnd, LocalTime.MAX);

        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);

        // 2. 通过POI将数据写入到Excel文件中
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        assert is != null;
        // 基于模板文件创建一个新的Excel文件
        XSSFWorkbook excel = new XSSFWorkbook(is);
        // 获取表格文件的sheet页
        XSSFSheet sheet = excel.getSheet("Sheet1");
        // 填充数据--时间
        sheet.getRow(1).getCell(1).setCellValue("时间: " + dateBegin + "至" + dateEnd);
        // 数据概览
        XSSFRow row = sheet.getRow(3);
        System.out.println("businessData:  " + businessData);
        row.getCell(2).setCellValue(businessData.getTurnover());
        row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
        row.getCell(6).setCellValue(businessData.getNewUsers());

        XSSFRow row1 = sheet.getRow(4);
        row1.getCell(2).setCellValue(businessData.getValidOrderCount());
        row1.getCell(4).setCellValue(businessData.getUnitPrice());


        // 明细数据
        for (int i = 0; i < 30; i++) {
            LocalDate date = dateBegin.plusDays(i);
            BusinessDataVO businessData1 = workspaceService.getBusinessData
                    (LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
            XSSFRow row2 = sheet.getRow(7 + i);
            row2.getCell(1).setCellValue(String.valueOf(date));
            row2.getCell(2).setCellValue(businessData1.getTurnover());
            row2.getCell(3).setCellValue(businessData1.getValidOrderCount());
            row2.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
            row2.getCell(5).setCellValue(businessData1.getUnitPrice());
            row2.getCell(6).setCellValue(businessData1.getNewUsers());
        }


        // 3. 通过输出流将Excel下载
        ServletOutputStream os = response.getOutputStream();
        excel.write(os);

        os.close();
        excel.close();
    }
}















